package com.wusuowei.ucenter.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wusuowei.common.annotation.Log;
import com.wusuowei.common.constant.BusinessTypeEnum;
import com.wusuowei.common.utils.R;
import com.wusuowei.ucenter.model.po.SysUser;
import com.wusuowei.ucenter.model.po.SysUserRole;
import com.wusuowei.ucenter.model.vo.PageUserVo;
import com.wusuowei.ucenter.model.vo.UserPasswordVo;
import com.wusuowei.ucenter.service.ISysUserRoleService;
import com.wusuowei.ucenter.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author LGY
 */
@Slf4j
@PreAuthorize("isAuthenticated()")
@RestController
@RequestMapping("user")
public class SysUserController {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysUserRoleService userRoleService;


    @PreAuthorize("hasAuthority('system:user:list')")
    @GetMapping("/page")
    public Map<String, Object> findPage(PageUserVo pagequery) {
        List<SysUser> all = userService.findPage(pagequery);
        List<SysUser> users = CollectionUtil.sub(all, (pagequery.getPageNum() - 1) * pagequery.getPageSize(), pagequery.getPageNum() * pagequery.getPageSize());
        HashMap<String, Object> map = new HashMap<>();
        map.put("records",users);
        map.put("total",all.size());
        return R.ok().setData(map);
    }

    /**
     * 查询用户数据详细
     */
    @PreAuthorize("hasAuthority('system:user:query')")
    @GetMapping(value = "/{userId}")
    public R getInfo(@PathVariable String userId)
    {
        SysUser sysUser = userService.getById(userId);
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId,userId);
        List<Integer> roleIds = userRoleService.list(wrapper).stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        sysUser.setRoleid(roleIds);
        return R.ok().setData(sysUser);
    }

    @PreAuthorize("hasAuthority('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessTypeEnum.INSERT)
    @Transactional
    @PostMapping
    public R add(@RequestBody SysUser sysUser) {
        // 新增或者更新
        //设置默认密码
        sysUser.setPassword(DigestUtils.md5DigestAsHex("123".getBytes()));
        userService.save(sysUser);
        SysUserRole sysUserRole = new SysUserRole();

        sysUserRole.setUserId(sysUser.getId());

        if(sysUser.getRoleid()!=null){
            //把原来的关系删了
            userRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, sysUserRole.getUserId()));
            //在进行添加
            for (Integer roleid : sysUser.getRoleid()) {
                sysUserRole.setRoleId(roleid);
                userRoleService.save(sysUserRole);
            }
        }
        return R.ok();
    }

    @PreAuthorize("hasAuthority('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping
    public R edit(@RequestBody SysUser sysUser)
    {
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(sysUser.getId());
        if(sysUser.getRoleid()!=null){
            //把原来的关系删了
            userRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, sysUserRole.getUserId()));
            //在进行添加
            for (Integer roleid : sysUser.getRoleid()) {
                sysUserRole.setRoleId(roleid);
                userRoleService.save(sysUserRole);
            }
        }
        return R.ok().setData(userService.updateById(sysUser));
    }

    /**
     * @description 删除
     * @param userIds
     * @return {@link R }
     * @author LGY
     * @date 2023/03/24 21:10
     */
    @PreAuthorize("hasAuthority('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessTypeEnum.DELETE)
    @DeleteMapping("/{userIds}")
    public R deleteBatch(@PathVariable List<String> userIds) {
        userService.removeBatchByIds(userIds);
        userRoleService.remove(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId,userIds));
        return R.ok();
    }

    /**
     * @description 根据用户名返回用户
     * @param username 用户名
     * @return {@link R }
     * @author LGY
     * @date 2023/03/24 21:09
     */
    @GetMapping("/username/{username}")
    public R getByUsername(@PathVariable String username) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername,username);
        SysUser one = userService.getOne(wrapper);
        return R.ok().setData(one);
    }

    @Log(title = "修改密码", businessType = BusinessTypeEnum.UPDATE)
    @PostMapping("/password")
    public R password(@RequestBody UserPasswordVo userPasswordVo) {
        userPasswordVo.setPassword(DigestUtils.md5DigestAsHex(userPasswordVo.getPassword().getBytes()));
        userPasswordVo.setNewPassword(DigestUtils.md5DigestAsHex(userPasswordVo.getNewPassword().getBytes()));
        try {
            userService.updatePassword(userPasswordVo);
        } catch (Exception e) {
            return R.error("原密码错误");
        }
        return R.ok();
    }

    @PreAuthorize("hasAuthority('system:user:ordinary')")
    @Log(title = "修改个人信息", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping("/updateUser")
    public R updateUser(@RequestBody SysUser sysUser)
    {
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(sysUser.getId());
        return R.ok().setData(userService.updateById(sysUser));
    }
}
